<%--
  Created by IntelliJ IDEA.
  User: lt
  Date: 2018/6/4
  Time: 19:22
  To change this template use File | Settings | File Templates.
--%>
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib uri="http://shiro.apache.org/tags" prefix="shiro" %>
<c:set var="contextPath" value="${pageContext.request.contextPath}"></c:set>
<c:set var="id" value="${pageContext.request.getParameter('id')}"></c:set>

<title>紧俏烟申购 - 紧俏烟信息</title>

<link rel="stylesheet" href="${contextPath}/static/ace/components/_mod/jquery-ui/jquery-ui.css"/>
<link rel="stylesheet"
      href="${contextPath}/static/ace/components/bootstrap-datepicker/dist/css/bootstrap-datepicker3.css"/>
<link rel="stylesheet" href="${contextPath}/static/ace/components/_mod/jqgrid/ui.jqgrid.css"/>
<link href="${contextPath}/static/ztree/css/zTreeStyle.css" rel="stylesheet" />
<script src="${contextPath}/static/statistics/js/bootstrap-datetimepicker.min.js"></script>
<script src="${contextPath}/static/statistics/js/bootstrap-datetimepicker.zh-CN.js"></script>
<script type="text/javascript" src="${contextPath}/static/statistics/js/jquery.mockjax.js"></script>
<!-- 商品列表详情 -->
<script type="text/javascript" src="${contextPath}/static/franchisee/alertProdInfo.js"></script>
<script src="${contextPath}/static/statistics/js/vue.js"></script>
<script src="${contextPath}/static/countjs/regularYz.js"></script>
<style type="text/css">
    .customBtn {
        line-height: 20px;
        margin-bottom: 3px;
    }

    .btnLine {
        margin-left: 1px;
        margin-top: 8px;
        margin-bottom: 2px;
    }

    @-webkit-keyframes bouncedelay {
        0%, 80%, 100% {
            -webkit-transform: scale(0.0)
        }
        40% {
            -webkit-transform: scale(1.0)
        }
    }

    @keyframes bouncedelay {
        0%, 80%, 100% {
            transform: scale(0.0);
            -webkit-transform: scale(0.0);
        }
        40% {
            transform: scale(1.0);
            -webkit-transform: scale(1.0);
        }
    }

    .autocomplete-suggestions {
        border: 1px solid #999;
        background: #FFF;
        overflow: auto;
    }

    .autocomplete-suggestion {
        padding: 2px 5px;
        white-space: nowrap;
        overflow: hidden;
    }

    .autocomplete-selected {
        background: #F0F0F0;
    }

    .autocomplete-suggestions strong {
        font-weight: normal;
        color: #3399FF;
    }

    @-moz-document url-prefix() {
        fieldset {
            display: table-cell;
        }
    }

    .ui-jqgrid .ui-priority-secondary{
        background: #d5effc;
    }

    .ui-jqgrid .ui-jqgrid-title{font-size:12px;}    /*修改grid标题的字体大小*/

    .ui-jqgrid-sortable {font-size:12px;}   /*修改列名的字体大小*/

    .ui-jqgrid tr.jqgrow td {font-size:12px; font-family:"宋体"} /*修改表格内容字体*/

    .ui-jqgrid-sortable {
        text-align: center;
    }

    .ui-jqgrid-sortable input{
        text-align: right;
    }

    .SelectBG{
        background-color:red;
    }

    .ui-pg-div{
        display: none;
    }
</style>

<div class="row" id="app">
    <div class="row btnLine">
        <div class="button-len col-sm-12">
            <div style="width: 100%; margin-bottom: 10px;">
                <button class="btn btn-white btn-sm btn-purple customBtn"  id="addProduct">
                    <i class="ace-icon fa fa-plus-circle purple"></i> 新增商品
                </button>
                <%--<button class="btn btn-white btn-info btn-sm customBtn" id="addReqOrder">--%>
                <%--<i class="ace-icon fa fa-pencil blue"></i> 生成采购单--%>
                <%--</button>--%>

                <button class="btn btn-white btn-info btn-sm customBtn" id="approval">
                    <i class="ace-icon fa fa-pencil blue"></i> 卷烟中心审批
                </button>

                <button class="btn btn-white btn-info btn-sm customBtn" id="confirm">
                    <i class="ace-icon fa fa-pencil blue"></i> 营销中心确实
                </button>

                <%--<label style="">采购类型：</label>--%>
                <%--<select class="input-sm" id="orderType">--%>
                    <%--<option value="1">统一采购单</option>--%>
                    <%--<option value="2">门店采购单</option>--%>
                <%--</select>--%>

                <%--<button class="btn btn-white btn-sm btn-purple customBtn" id="roleAuthorization">--%>
                <%--<i class="ace-icon fa fa-plus-circle purple"></i> 测试按钮--%>
                <%--</button>--%>
                <%--<button class="btn btn-white btn-info btn-sm customBtn" id="deleteSupplier">--%>
                <%--<i class="ace-icon fa fa-key red"></i> 删除--%>
                <%--</button>--%>
                <%--<button class="btn btn-white btn-info btn-sm customBtn" id="">--%>
                <%--<i class="ace-icon fa fa-key red"></i> 复制--%>
                <%--</button>--%>
                <%--<button class="btn btn-white btn-info btn-sm customBtn" id="">--%>
                <%--<i class="ace-icon fa fa-key red"></i> 打印--%>
                <%--</button>--%>
                <%--<button class="btn btn-white btn-info btn-sm customBtn" id="">--%>
                <%--<i class="ace-icon fa fa-key red"></i> 导出--%>
                <%--</button>--%>
                <%--<button class="btn btn-white btn-info btn-sm customBtn" id="">--%>
                <%--<i class="ace-icon fa fa-key red"></i> 设置--%>
                <%--</button>--%>
                <%--<button class="btn btn-white btn-info btn-sm customBtn" id="">--%>
                <%--<i class="ace-icon fa fa-key red"></i> 退出--%>
                <%--</button>--%>
                <input class="input-sm" type="text" id="keyword" style="margin-left: 0px;" value=""
                       placeholder="关键字">
                <button class="btn btn-sm btn-white btn-info search-len customBtn"
                        onclick="searchShop()">
                    <i class="ace-icon fa fa-search orange"></i>搜索
                </button>
            </div>
        </div>
    </div>
    <!-- 内容数据开始 -->
    <div class="col-xs-12">
        <table id="grid-table"></table>

        <div id="grid-pager"></div>

    </div>

    <!-- 内容数据结束 -->

    <!-- 商品模态框（Modal） -->
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog" style="width: 840px;">
            <div class="modal-content">
                <div class="modal-header" style="font-size: 20px; margin-bottom: -15px;">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                        &times;
                    </button>
                    <h4 class="modal-title" id="myModalLabel">
                        退货 - <span id="alertTitle">商品新增</span>
                        <small id="smallTitle" class="hide" style="color: red; float: right; margin-top: 10px;"></small>
                    </h4>
                </div>
                <div class="modal-body">
                    <div class="row" style="height: 100px;">
                        <table class="table">
                            <tbody>
                            <tr>
                                <th>
                                    <div class="row btnLine">
                                        <div class="button-len col-sm-12">
                                            <label for="" style="margin-left: 8px;">商品类型：</label>
                                            <select class="input-sm" id="isExpInput">
                                                <option value="0">商品类型</option>
                                                <option :value="obj.typeId" v-for="(obj, index) in yanType1">
                                                    {{ obj.typeName }}
                                                </option>

                                            </select>
                                            <select class="input-sm" id="isAuthInput">
                                                <option value="-1">商品大类</option>
                                                <option :value="obj.typeId" v-for="(obj, index) in yanType2">
                                                    {{ obj.typeName }}
                                                </option>
                                            </select>

                                            <select class="input-sm" id="isAuthInput1">
                                                <option value="-1">商品中类</option>
                                                <option :value="obj.typeId" v-for="(obj, index) in yanType3">
                                                    {{ obj.typeName }}
                                                </option>
                                            </select>

                                            <select class="input-sm" id="isAuthInput2">
                                                <option value="-1">商品小类</option>
                                                <option :value="obj.typeId" v-for="(obj, index) in yanType4">
                                                    {{ obj.typeName }}
                                                </option>
                                            </select>
                                        </div>
                                    </div>
                                </th>
                            </tr>
                            <tr>
                                <th>
                                    <input class="input-sm" type="text" id="productCode" style="margin-left: 20px;"
                                           placeholder="商品条码">
                                    <input class="input-sm" type="text" id="productName" style="margin-left: 5px;"
                                           placeholder="商品名称">
                                    <button class="btn btn-sm btn-white btn-info search-len customBtn"
                                            onclick="searchShopProduct(grid_prod_selector)">
                                        <i class="ace-icon fa fa-search orange"></i>搜索
                                    </button>
                                </th>
                            </tr>
                            </tbody>
                        </table>
                    </div>
                    <!-- 内容数据开始 -->
                    <div class="button-len col-sm-12">
                        <table id="grid-prod-table"></table>
                        <div id="grid-prod-pager"></div>
                    </div>
                    <!-- 内容数据结束 -->
                    <div style="text-align: right;">
                        <button class="btn btn-white btn-info btn-sm customBtn btn-xs" type="button" id="appProd" style="margin-top: 10px; margin-right: 11px;">添加</button>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default btn-xs" data-dismiss="modal" v-on:click="close">关闭</button>
                    <%--<button type="button" class="btn btn-primary btn-xs" v-on:click="saveSupplier">提交更改</button>--%>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal -->
    </div>


</div>

<!-- 通用变量 -->
<script type="text/javascript">
    var lastsel;
    var SelectRowIndx;
    var grid_selector = "#grid-table";
    var pager_selector = "#grid-pager";

    var grid_prod_selector = "#grid-prod-table";
    var pager_prod_selector = "#grid-prod-pager";

    var laypage = layui.laypage,
        layer = layui.layer
    laydate = layui.laydate;

    //请求数据集
    var queryModel = {
        //分页参数
        page: '1',
        rows: '10',
        parentId: '',
        commodityIds: [],
    }

    //jqGrid 页面加载完带参数请求
    var filters = {
        "rules": [
            {
                "field": "state",
                "data": '1'
            }
        ]
    };
    var grid_data = {'filters': JSON.stringify(filters)};
    console.log(grid_data)
</script>

<!-- Vue实现类 -->
<script type="text/javascript">

    var app = new Vue({
        el: '#app',
        data: {
            objcte: [],
            priceTypeArray: [],
            parentArray: [],
            arrayShop: [],
            yanType1: [],
            yanType2: [],
            yanType3: [],
            yanType4: [],
            yanType5: [],
        },
        methods: {

        }
    })
</script>

<!-- 事件实现 -->
<script type="text/javascript">

    //新增商品
    $("#addProduct").click(function () {
        prodInfo('${contextPath}', grid_prod_selector, pager_prod_selector);
        $('#myModal').modal('show');
    })

    $("#approval").click(function () {
        approval()
    });

    $("#confirm").click(function () {
        confirm()
    });

    $("#appProd").click(function () {
        addRowData();
    })
    //
    $("#xia").click(function () {
        $("#detail").css('background-color','#f5f5f5');
        $("#basics").css('background-color','#FFFFFF');
        $("#detail").css('border-radius','12px 0px 12px 0px');
        $("#basics").css('border-radius', '0px');
        $("#table1").addClass("hide");
        $("#table3").removeClass("hide");
        $("#xia").addClass("hide");
        $("#shang").removeClass("hide");
    });

    $("#shang").click(function () {
        $("#basics").css('background-color','#f5f5f5');
        $("#detail").css('background-color','#FFFFFF');
        $("#basics").css('border-radius','12px 0px 12px 0px');
        $("#detail").css('border-radius', '0px');
        $("#table3").addClass("hide");
        $("#table1").removeClass("hide");
        $("#shang").addClass("hide");
        $("#xia").removeClass("hide");
    });

    $("#basics").click(function () {
        $("#detail").css('background-color','#f5f5f5');
        $("#basics").css('background-color','#FFFFFF');
        $("#basics").css('border-radius','12px 0px 12px 0px');
        $("#detail").css('border-radius', '0px');
        $("#table3").addClass("hide");
        $("#table1").removeClass("hide");
        $("#xia").addClass("hide");
        $("#shang").removeClass("hide");
    });

    $("#detail").click(function () {
        $("#detail").css('background-color','#FFFFFF');
        $("#basics").css('background-color','#f5f5f5');
        $("#detail").css('border-radius','12px 0px 12px 0px');
        $("#basics").css('border-radius', '0px');
        $("#table1").addClass("hide");
        $("#table3").removeClass("hide");
        $("#shang").removeClass("hide");
        $("#xia").addClass("hide");
    });

    /************* 时间事件 **************/
    //开始时间
    $('#beginTime').datetimepicker({
        language: 'zh-CN',
        weekStart: 1,
        todayBtn: 1,
        autoclose: 1,
        todayHighlight: 1,
        startView: 2,
        forceParse: 0,
        minView: 2,
        showMeridian: 1,
        format: "yyyy-mm-dd",
//        startDate:new Date(),
    });

    //结束时间
    $('#endTime').datetimepicker({
        language: 'zh-CN',
        weekStart: 1,
        todayBtn: 1,
        autoclose: 1,
        todayHighlight: 1,
        startView: 2,
        forceParse: 0,
        minView: 2,
        showMeridian: 1,
        format: "yyyy-mm-dd",
//        startDate:new Date(),
    });

    //促销开始时间
    $('#promotionBeginTime').datetimepicker({
        language: 'zh-CN',
        weekStart: 1,
        todayBtn: 1,
        autoclose: 1,
        todayHighlight: 1,
        startView: 2,
        forceParse: 0,
        minView: 2,
        showMeridian: 1,
        format: "yyyy-mm-dd",
//        startDate:new Date(),
    });

    //促销结束时间
    $('#promotionEndTime').datetimepicker({
        language: 'zh-CN',
        weekStart: 1,
        todayBtn: 1,
        autoclose: 1,
        todayHighlight: 1,
        startView: 2,
        forceParse: 0,
        minView: 2,
        showMeridian: 1,
        format: "yyyy-mm-dd",
//        startDate:new Date(),
    });

    //促销开始时间
    $('#promotionBeginTimeHH').datetimepicker({
        language: 'zh-CN',
        weekStart: 1,
        todayBtn: 1,
        autoclose: 1,
        todayHighlight: 1,
        startView: 2,
        forceParse: 0,
        minView: 2,
        showMeridian: 1,
        format: "hh:mm:ss",
//        startDate:new Date(),
    });

    //促销结束时间
    $('#promotionEndTimeHH').datetimepicker({
        language: 'zh-CN',
        weekStart: 1,
        todayBtn: 1,
        autoclose: 1,
        todayHighlight: 1,
        startView: 2,
        forceParse: 0,
        minView: 2,
        showMeridian: 1,
        format: "hh:mm:ss",
//        startDate:new Date(),
    });

    //终止时间
    $("#terminationTime").datetimepicker({
        language: 'zh-CN',
        weekStart: 1,
        todayBtn: 1,
        autoclose: 1,
        todayHighlight: 1,
        startView: 2,
        forceParse: 0,
        minView: 2,
        showMeridian: 1,
        format: "yyyy-mm-dd",
//        startDate:new Date(),
    });

    //操作时间
    $("#operationTime").datetimepicker({
        language: 'zh-CN',
        weekStart: 1,
        todayBtn: 1,
        autoclose: 1,
        todayHighlight: 1,
        startView: 2,
        forceParse: 0,
        minView: 2,
        showMeridian: 1,
        format: "yyyy-mm-dd",
//        startDate:new Date(),
    });

    //审核时间
    $("#checkTime").datetimepicker({
        language: 'zh-CN',
        weekStart: 1,
        todayBtn: 1,
        autoclose: 1,
        todayHighlight: 1,
        startView: 2,
        forceParse: 0,
        minView: 2,
        showMeridian: 1,
        format: "yyyy-mm-dd",
//        startDate:new Date(),
    });
</script>

<!-- 调用方法 -->
<script type="text/javascript">

    /**
     * 确定
     **/
    var confirm = function () {
        var ids = $(grid_selector).jqGrid('getGridParam', 'selarrrow');
        var len = ids.length;
        if(len == 0){
            layer.msg("提示：您还没有选择商品");
            return
        }
        var prodList = [];
        for(var i=0;i<ids.length;i++) {
            var rowData = $(grid_selector).jqGrid('getRowData', ids[i]);
            var confirmQuantity_id = "#confirmQuantity-"+rowData.productCode;
            var confirmQuantity = $(confirmQuantity_id).val();
            if (confirmQuantity == '' || confirmQuantity == 0){
                layer.msg("提示：中心确定数量必须大于 0 ！")
                return
            }
            var array = {};
            array.productCode = rowData.productCode;
            array.requireQuantity = rowData.requireQuantity;
            array.confirmQuantity = confirmQuantity;
            prodList.push(array);
        }
        queryModel.prodList = JSON.stringify(prodList);
        console.log(queryModel);

        layer.confirm('是否确定审批商品？', {
            btn: ['确定', '取消'] //按钮
        }, function () {

            layer.load(1);
            $.ajax({
                url: '${contextPath}/ktProd/saveTightTobacco',
                type: 'post',
                data: queryModel,
                success: function (data) {
                    layer.closeAll('loading');
                    if (data.success == false){
                        layer.msg("获取出错："+data.message)
                        return
                    }
                    var dataArray = data;
                    layer.msg("提示："+data.message)
                    reload();
                },
                error: function (error) {
                    layer.closeAll('loading')
                }
            })
        })
    }

    /**
     * 审批
     **/
    var approval = function () {
        var ids = $(grid_selector).jqGrid('getGridParam', 'selarrrow');
        var len = ids.length;
        if(len == 0){
            layer.msg("提示：您还没有选择商品");
            return
        }

        var prodList = [];
        for(var i=0;i<ids.length;i++) {
            var rowData = $(grid_selector).jqGrid('getRowData', ids[i]);
            var confirmQuantity_id = "#confirmQuantity-"+rowData.productCode;
            var confirmQuantity = $(confirmQuantity_id).val();
            if (confirmQuantity == '' || confirmQuantity == 0){
                layer.msg("提示：中心确定数量必须大于 0 ！")
                return
            }

            var array = {};
            array.productCode = rowData.productCode;
            array.requireQuantity = rowData.requireQuantity;
            array.confirmQuantity = confirmQuantity;
            prodList.push(array);
        }
        queryModel.prodList = JSON.stringify(prodList);

        console.log(queryModel);

        layer.confirm('是否确定审批商品？', {
            btn: ['确定', '取消'] //按钮
        }, function () {
            layer.load(1);
            $.ajax({
                url: '${contextPath}/ktProd/deleteTightTobacco',
                type: 'post',
                data: queryModel,
                success: function (data) {
                    layer.closeAll('loading');
                    if (data.success == false){
                        layer.msg("获取出错："+data.message)
                        return
                    }
                    var dataArray = data;
                    layer.msg("提示："+data.message)
                    reload();
                },
                error: function (error) {
                    layer.closeAll('loading')
                    layer.msg("提示："+data.message);
                }
            })
        })
    }

    /**
     * 搜索店铺
     */
    function searchShopInfo() {

//        $('#myModal').modal('show');


        var shopType = $("#shopType").val();
        var shopName = $("#shopName").val();
//        if (priceType == "0"){
//            layer.msg("提示：请选择价格类型！")
//            return
//        }
        console.log(shopName);
        var filters = {
            "rules": [
                {
                    "field": "shopName",
                    "data": shopName
                },
                {
                    "field": "shopType",
                    "data": shopType
                }
            ]
        };
        console.log(filters);

        jQuery("#grid-shop-table").jqGrid('setGridParam', {
            postData: {
                "filters": JSON.stringify(filters) //"{'rules' : [{'field' : 'shopName','data' : "+shopName+"},{'field' : 'state','data' : "+state+"}]}"
            }
        }).trigger("reloadGrid");
    }

    var submitReq = function () {
//        var id = $(grid_selector).jqGrid('getGridParam', 'selrow');
        var ids = $(grid_selector).jqGrid('getGridParam', 'selarrrow');
        if (ids.length == 0){
            layer.msg("你没有选择添加商品！");
            return;
        }
        var prodList = [];
        for(var i=0;i<ids.length;i++){
            var quantityId = "#quantity_"+ids[i];
            var rowData = $(grid_selector).jqGrid('getRowData', ids[i]);
            var idArray = {};
            idArray.productCode = rowData.productCode;
            idArray.requireShopId = rowData.requireShopId.split('>')[1].split('<')[0];
            var quantity = $(quantityId).val();
            console.log(quantity)
            if (quantity == '0'){
                layer.msg("提示："+rowData.productName+"商品没有要货数不能为0！");
                return;
            }
            idArray.quantity = quantity;
            prodList.push(idArray);
        }
        prodList.id = idArray;
//        console.log(JSON.stringify(prodList));
        queryModel.prodList = JSON.stringify(prodList);
        console.log(queryModel)
//        queryModel.id = id;
        $.ajax({
            url: '${contextPath}/ktPurchase/saveShopRequireOrder',
            type: 'post',
            data: queryModel,
            success: function (data) {
//                layer.closeAll('loading');
                if (data.success == false){
                    layer.msg("获取出错："+data.message)
                    return
                }
                var dataArray = data;
                layer.msg("提示："+data.message)
                reload()
            },
            error: function (error) {
//                layer.closeAll('loading')
            }
        })
    }

    /*************  新增商品 **********/
    /*2.把dataRow添加到表格中*/
    var lenNr = 0;
    function addRowData(){
        var ids = $(grid_prod_selector).jqGrid('getGridParam', 'selarrrow');
        var len = ids.length;
        if(len == 0){
            layer.msg("提示：您还没有选择商品");
            return
        }
        for(var i=0;i<len;i++) {
            var rowData = $(grid_prod_selector).jqGrid('getRowData', ids[i]);
            var productCode = rowData.productCode;
            getProdSupplier(productCode);
            rowData.requireShopName = rowData.supplierName;
            rowData.requireShopId = rowData.supplierId;
            console.log(rowData)
            if(vyProductCode(productCode)){
                console.log(lenNr)
                $(grid_selector).jqGrid("addRowData", lenNr, rowData, "first");
                lenNr++;
            }else {
                layer.msg("提示：商品已经添加");
                return;
            }
        }
    }
    //判断商品是否添加
    var vyProductCode = function (productCode) {
        var str = true;
        var idsGr = $(grid_selector).jqGrid("getRowData");
        jQuery(idsGr).each(function(){
            var productCodeGr = this.productCode;
            if (productCode == productCodeGr) {
                str = false;
            }
        });
        return str;
    }

    //根据productCode 获取供应商
    var getProdSupplier = function (productCode) {
        var dataList = {};
        dataList.productCode = productCode;
        $.ajax({
            url: '${contextPath}/ktProd/getProdSupplier',
            type: 'post',
            data: dataList,
            success: function (data) {
                var dataArray = data;
//                console.log(data);
                var supplierName = dataArray.supplierName;
                var supplierId = dataArray.supplierId;

            },
            error: function (error) {
            }
        })
    }
    /**************************************/

    /**
     * 搜索店铺
     */
    function searchShop() {
        var keyword = $("#keyword").val();
//        var phone = $("#phone").val();
        //var parentDepartmentkey = $("#id_parentDepartmentkey_name").val();

        var filters = {
            "rules": [{
                "field": "keyword",
                "data": keyword
            }]
        };
        jQuery("#grid-table").jqGrid('setGridParam', {
            postData: {
                "filters": JSON.stringify(filters) //"{'rules' : [{'field' : 'shopName','data' : "+shopName+"},{'field' : 'state','data' : "+state+"}]}"
            }
        }).trigger("reloadGrid");
    }


    var reload = function () {
//        $(grid_selector).jqGrid('clearGridData');  //清空表格
        $(grid_selector).jqGrid('setGridParam',{
            url:"${contextPath}/ktProd/getCenterRecommendTightTobaccoByPage",
            datatype:'json',
//                    postData:param,
            page:1
        }).trigger("reloadGrid"); //重新载入
    }

    $('#shopId').change(function () {
        var shopId = $("#shopId").val();
//        var phone = $("#phone").val();
        //var parentDepartmentkey = $("#id_parentDepartmentkey_name").val();

        var filters = {
            "rules": [
                {
                    "field": "shopId",
                    "data": shopId
                }
            ]
        };
        console.log(filters)
        jQuery("#grid-table").jqGrid('setGridParam', {
            postData: {
                "filters": JSON.stringify(filters) //"{'rules' : [{'field' : 'shopName','data' : "+shopName+"},{'field' : 'state','data' : "+state+"}]}"
            }
        }).trigger("reloadGrid");
    })

    /*************** 数据验证 *******************/
    var requireQuantityVerify = function (productCode) {
        var requireQuantity_id = "#requireQuantity-"+productCode;
        var requireQuantity = $(requireQuantity_id).val();
        if(!integerVerify(requireQuantity)){
            console.log(requireQuantity);
            $(requireQuantity_id).val(0);
            return
        }
    }

    var confirmQuantityVerify = function (productCode) {
        var confirmQuantity_id = "#confirmQuantity-"+productCode;
        var confirmQuantity = $(confirmQuantity_id).val();
        if(!integerVerify(confirmQuantity)){
            console.log(!integerVerify(confirmQuantity));
            $(confirmQuantity_id).val(0);
            return
        }
    }
    /**********************************/

    /**
     * 搜索商品

    var searchShopProduct = function() {
        var supplierName = $("#supplierName").val();
        var productCode = $("#productCode").val();
        var state = $("#state1").val();
        var productName = $("#productName").val();
        var typeId = queryModel.parentId == null ? "0" : queryModel.parentId;
        //var parentDepartmentkey = $("#id_parentDepartmentkey_name").val();

        var filters = {
            "rules": [
                {"field": "productCode", "data": productCode},
                {"field": "productName", "data": productName},
//                {"field": "supplierName", "data": supplierName},
                {"field": "typeId", "data": typeId},
//                {"field": "state", "data": state}
            ]
        };
        console.log(JSON.stringify(filters))
        jQuery(grid_prod_selector).jqGrid('setGridParam', {
            postData: {
                "filters": JSON.stringify(filters) //"{'rules' : [{'field' : 'shopName','data' : "+shopName+"},{'field' : 'state','data' : "+state+"}]}"
            }
        }).trigger("reloadGrid");
    }
     */
</script>

<!-- 复用jqGrid 方法 -->
<script type="text/javascript">

    //选中行启用行编辑
    var EditSelectRow = function(grid_id, id) {
        //原选中行ID
        if (id != null && id != "" && id.length > 0) {
            $(grid_id).jqGrid('saveRow', id);//保存上一行
        }
        //当前选中行
        $(grid_id).val(id);//临时存储当前选中行
//        $(grid_id).jqGrid('editRow', id);
        $(grid_id).jqGrid('editRow', id, {keys: true, focusField: 1});
    }

    function style_edit_form(form) {
        //enable datepicker on "sdate" field and switches for "stock" field
        //form.find('input[name=sdate]').datepicker({format:'yyyy-mm-dd' , autoclose:true})

        //form.find('input[name=stock]').addClass('ace ace-switch ace-switch-5').after('<span class="lbl"></span>');
        //don't wrap inside a label element, the checkbox value won't be submitted (POST'ed)
        //.addClass('ace ace-switch ace-switch-5').wrap('<label class="inline" />').after('<span class="lbl"></span>');


        //update buttons classes
        var buttons = form.next().find('.EditButton .fm-button');
        buttons.addClass('btn btn-sm').find('[class*="-icon"]').hide();//ui-icon, s-icon
        buttons.eq(0).addClass('btn-primary').prepend('<i class="ace-icon fa fa-check"></i>');
        buttons.eq(1).prepend('<i class="ace-icon fa fa-times"></i>')

        buttons = form.next().find('.navButton a');
        buttons.find('.ui-icon').hide();
        buttons.eq(0).append('<i class="ace-icon fa fa-chevron-left"></i>');
        buttons.eq(1).append('<i class="ace-icon fa fa-chevron-right"></i>');
    }

    function style_delete_form(form) {
        var buttons = form.next().find('.EditButton .fm-button');
        buttons.addClass('btn btn-sm btn-white btn-round').find('[class*="-icon"]').hide();//ui-icon, s-icon
        buttons.eq(0).addClass('btn-danger').prepend('<i class="ace-icon fa fa-trash-o"></i>');
        buttons.eq(1).addClass('btn-default').prepend('<i class="ace-icon fa fa-times"></i>')
    }

    function style_search_filters(form) {
        form.find('.delete-rule').val('X');
        form.find('.add-rule').addClass('btn btn-xs btn-primary');
        form.find('.add-group').addClass('btn btn-xs btn-success');
        form.find('.delete-group').addClass('btn btn-xs btn-danger');
    }

    function style_search_form(form) {
        var dialog = form.closest('.ui-jqdialog');
        var buttons = dialog.find('.EditTable')
        buttons.find('.EditButton a[id*="_reset"]').addClass('btn btn-sm btn-info').find('.ui-icon').attr('class', 'ace-icon fa fa-retweet');
        buttons.find('.EditButton a[id*="_query"]').addClass('btn btn-sm btn-inverse').find('.ui-icon').attr('class', 'ace-icon fa fa-comment-o');
        buttons.find('.EditButton a[id*="_search"]').addClass('btn btn-sm btn-purple').find('.ui-icon').attr('class', 'ace-icon fa fa-search');
    }

    function beforeDeleteCallback(e) {
        var form = $(e[0]);
        if (form.data('styled')) return false;

        form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
        style_delete_form(form);
        form.data('styled', true);
    }

    function beforeEditCallback(e) {
        var form = $(e[0]);
        form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
        style_edit_form(form);
    }


    //it causes some flicker when reloading or navigating grid
    //it may be possible to have some custom formatter to do this as the grid is being created to prevent this
    //or go back to default browser checkbox styles for the grid
    function styleCheckbox(table) {
        /**
         $(table).find('input:checkbox').addClass('ace')
         .wrap('<label />')
         .after('<span class="lbl align-top" />')


         $('.ui-jqgrid-labels th[id*="_cb"]:first-child')
         .find('input.cbox[type=checkbox]').addClass('ace')
         .wrap('<label />').after('<span class="lbl align-top" />');
         */
    }


    //unlike navButtons icons, action icons in rows seem to be hard-coded
    //you can change them like this in here if you want
    function updateActionIcons(table) {
        /**
         var replacement =
         {
             'ui-ace-icon fa fa-pencil' : 'ace-icon fa fa-pencil blue',
             'ui-ace-icon fa fa-trash-o' : 'ace-icon fa fa-trash-o red',
             'ui-icon-disk' : 'ace-icon fa fa-check green',
             'ui-icon-cancel' : 'ace-icon fa fa-times red'
         };
         $(table).find('.ui-pg-div span.ui-icon').each(function(){
				var icon = $(this);
				var $class = $.trim(icon.attr('class').replace('ui-icon', ''));
				if($class in replacement) icon.attr('class', 'ui-icon '+replacement[$class]);
			})
         */
    }

    //replace icons with FontAwesome icons like above
    function updatePagerIcons(table) {
        var replacement =
            {
                'ui-icon-seek-first': 'ace-icon fa fa-angle-double-left bigger-140',
                'ui-icon-seek-prev': 'ace-icon fa fa-angle-left bigger-140',
                'ui-icon-seek-next': 'ace-icon fa fa-angle-right bigger-140',
                'ui-icon-seek-end': 'ace-icon fa fa-angle-double-right bigger-140'
            };
        $('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function () {
            var icon = $(this);
            var $class = $.trim(icon.attr('class').replace('ui-icon', ''));

            if ($class in replacement) icon.attr('class', 'ui-icon ' + replacement[$class]);
        })
    }

    function enableTooltips(table) {
        $('.navtable .ui-pg-button').tooltip({container: 'body'});
        $(table).find('.ui-pg-div').tooltip({container: 'body'});
    }

    //var selr = jQuery(grid_promotion_selector).jqGrid('getGridParam','selrow');

//    $(document).one('ajaxloadstart.page', function (e) {
//        $.jgrid.gridDestroy(grid_promotion_selector);
//        $('.ui-jqdialog').remove();
//    });

    var reload = function () {
//        $(grid_promotion_selector).jqGrid('clearGridData');  //清空表格
        $(grid_selector).jqGrid('setGridParam',{
            url:"${contextPath}/ktProd/getCenterRecommendTightTobaccoByPage",
            datatype:'json',
//                    postData:param,
            page:1
        }).trigger("reloadGrid"); //重新载入
    }
</script>

<!-- jqGrid加载数据 -->
<script type="text/javascript">
    var grid_data = '${id}';
    var scripts = [null, "${contextPath}/static/ace/components/bootstrap-datepicker/dist/js/bootstrap-datepicker.js", "${contextPath}/static/ace/components/jqGrid/js/jquery.jqGrid.js", "${contextPath}/static/ace/components/jqGrid/js/i18n/grid.locale-cn.js", "${contextPath}/static/layer/layer.js","${contextPath}/static/ztree/js/jquery.ztree.core-3.5.js", "${contextPath}/static/ztree/js/jquery.ztree.excheck-3.5.js", null]
    $('.page-content-area').ace_ajax('loadScripts', scripts, function () {

        jQuery(function ($) {

            var parent_column = $(grid_selector).closest('[class*="col-"]');
            //resize to fit page size
            $(window).on('resize.jqGrid', function () {
                $(grid_selector).jqGrid('setGridWidth', parent_column.width());
            })

            //resize on sidebar collapse/expand
            $(document).on('settings.ace.jqGrid', function (ev, event_name, collapsed) {
                if (event_name === 'sidebar_collapsed' || event_name === 'main_container_fixed') {
                    //setTimeout is for webkit only to give time for DOM changes and then redraw!!!
                    setTimeout(function () {
                        $(grid_selector).jqGrid('setGridWidth', parent_column.width());
                    }, 20);
                }
            })

            jQuery(grid_selector).jqGrid({
                subGrid: false,
                url : '${contextPath}/ktProd/getCenterRecommendTightTobaccoByPage',
                datatype: "json",
                mtype: 'POST',
//                styleUI: 'Bootstrap',//设置jqgrid的全局样式为bootstrap样式
                height: 350,
                colNames: ['id','商品名称', '类型', '条码','单位','规格', '现有库存', '要货数量', '中心确定数量'],
                colModel: [
                    {
                        name: 'id',
                        index: 'id',
                        hidden: true,
                        editable: false,
                        sortable: false
                    },
                    {
                        name: 'productName',
                        index: 'productName',
                        editable: false,
                        sortable: false,
                        editrules: {required: true}
                    },
                    {
                        name: 'prodTypeName',
                        index: 'prodTypeName',
                        editable: false,
                        hidden: true,
                        sortable: true,
                        editrules: {required: true}
                    },
                    {
                        name: 'productCode',
                        index: 'productCode',
                        editable: false,
                        sortable: false,
                        editrules: {required: true}
                    },
                    {
                        name: 'unit',
                        index: 'unit',
                        editable: false,
                        sortable: false
                    },
                    {
                        name: 'spec',
                        index: 'spec',
                        editable: false,
                        sortable: false,
                        formatter:function(cellvalue, options, rowObject) {
                            var spec = cellvalue;
                            if(!spec){
                                spec = '-'
                            }
                            return spec;
                        }
                    },
                    {
                        name: 'maxStock',
                        index: 'maxStock',
                        editable: false,
                        sortable: false,
                        hidden: true,
                        align: 'right',
                    },
                    {
                        name: 'requireQuantity',
                        index: 'requireQuantity',
                        editable: false,
                        sortable: false,
                        align: 'right',
//                        formatter:function(cellvalue, options, rowObject) {
//                            var productCode = rowObject.productCode;
//                            if(!cellvalue) {
//                                cellvalue = '-';
//                            }
//                            return '<input type="text" id="requireQuantity-' + productCode + '" name="requireQuantity" value="'+cellvalue+'" class="content" onblur="requireQuantityVerify('+productCode+')" size="" maxlength="" style="text-align: right;"/>';
//                        }
                    },
                    {
                        name: 'confirmQuantity',
                        index: 'confirmQuantity',
                        editable: true,
                        sortable: false,
                        align: 'right',
//                        formatter: function (v, x, r) {
//                            var total = r.total;
//                            var quantity = r.quantity;
//                            if (!quantity){
//                                return total;
//                            }
//                        }
                        formatter:function(cellvalue, options, rowObject) {
                            var productCode = rowObject.productCode;
                            var requireQuantity = rowObject.requireQuantity;
                            if(!cellvalue) {
                                cellvalue = requireQuantity;
                            }
                            return '<input type="text" id="confirmQuantity-' + productCode + '" name="confirmQuantity" value="'+cellvalue+'" class="content" onblur="confirmQuantityVerify('+productCode+')" size="" maxlength="" style="text-align: right;"/>';
                        }
                    },
                ],

//                rownumbers: true, //自动行数
//                height:"100%",   //高度自适应
//			width: "100%",
                autowidth: true,  //宽度自适应
                viewrecords: true,
                rowNum: 10,
                rowList: [10, 20, 30],
                pager: pager_selector,
                altRows: true,
                //toppager: true,

                multiselect: true,
                multiboxonly: false,

                loadonce: true, //一次加载全部数据到客户端，由客户端进行排序。
                sortable: true,
                sortname: 'zykj', //设置默认的排序列
                sortorder: 'asc',

//                rownumbers: true, // 显示行号
//                rownumWidth: 35, // the width of the row numbers columns
//                subGrid: false, //是否启用子表格

                loadComplete: function () {
                    var table = this;
                    setTimeout(function () {
                        styleCheckbox(table);
                        updateActionIcons(table);
                        updatePagerIcons(table);
                        enableTooltips(table);
                    }, 0);
                },

                //数据加载完成后判断数据值更变行背景色
                gridComplete: function () {
                    var ids = $(grid_selector).getDataIDs();
                    for (var i = 0; i < ids.length; i++) {
                        var rowData = $(grid_selector).getRowData(ids[i]);


                        var confirmQuantity_id = "#confirmQuantity-"+rowData.productCode;
                        var confirmQuantity = $(confirmQuantity_id).val();

                        var requireQuantity = rowData.requireQuantity;

                        if (requireQuantity  > confirmQuantity) {//如果审核不通过，则背景色置于红色
                            console.log(ids[i])
                            $('#' + ids[i]).removeClass("ui-priority-secondary")
                            $('#' + ids[i]).addClass("SelectBG");
                        }
                    }

                    $("#" + this.id).jqGrid('setSelection', SelectRowIndx);
                },

                editurl: "${contextPath}/ktProd/getCenterRecommendTightTobaccoByPage",//nothing is saved
                caption: "商品信息",
                jsonReader: {
                    root: "recordList",
                    page: "currentPage",
                    total: "pageCount",
                    records: "recordCount"
                },

                //单击
                onSelectRow : function(id) {

                },
                ondblClickRow: function (id) {
                    EditSelectRow(grid_selector ,id);
                    var rowData = $(grid_selector).jqGrid('getRowData', id);
                    var quantityId = '#'+id+'_quantity1';
                    rowData.quantity1 = $(quantityId).val()
                    console.log(rowData)
                }

//                ondblClickRow: function (id) {
//                    EditSelectRow(grid_selector ,id);
//                },
//
//                beforeSelectRow: function (id, e) {
//                    var quantityId = '#'+id+'_quantity1';
//                    var quantity = $(quantityId).val();
//                    if(realminVerify(quantity)){
//                        jQuery(grid_selector).saveRow(id);    // 隐藏input
//                        return;
//                    }
//                    layer.msg("提示：只能输入整数！")
//                    console.log(quantity)
//                    $(quantityId).val('');
//
//                },

                <%--editurl : '${contextPath}/ktProd/getCenterRecommendTightTobaccoByPage',--%>
                <%--caption : "Using events example"--%>
            });

            jQuery(grid_selector).jqGrid('navGrid', grid_selector, {
                edit : false,
                add : false,
                del : false
                //,autowidth: true,
            });

            // 设置jqgrid的宽度
//            $(window).bind('resize', function () {
//                var width = $('.jqGrid_wrapper').width();
//                jqGrid.setGridWidth(width);
//            });


            $(window).triggerHandler('resize.jqGrid');//trigger window resize to make the grid get the correct size


            /**
             * 修改某条信息
             */
            $("#editShop").click(function () {
                var id = $(grid_selector).jqGrid('getGridParam', 'selrow');

                var rowData = $(grid_selector).jqGrid('getRowData', id);
                if (!id) {
                    layer.msg("提示：", "请选择一条信息");
                    return;
                }
                if(rowData.state != "待提交"){
                    layer.msg("提示：", "订单已提交不能修改");
                    return;
                }
                $(grid_selector).jqGrid("editGridRow", id, {
                    // edit record form
                    width: 500,
                    closeAfterEdit: true,
                    //editData :
                    recreateForm: true,
                    viewPagerButtons: false,
                    beforeShowForm: function (e) {
                        var form = $(e[0]);
                        form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar')
                            .wrapInner('<div class="widget-header" />');
                        style_edit_form(form);
                    },
                    afterShowForm: function (e) {
                        var form = $(e[0]);
                        //console.log(form)
                    },
                    afterSubmit: function (response, postdata) {
                        var result = eval('(' + response.responseText + ')');
                        ////console.log(result);
                        return [result.success, result.message, 0];
                    },
                    errorTextFormat: function (response) {
                        ////console.log("错误"+response.responseText);
                        //var result = response.responseText;
                        return "服务器异常，稍后再试";
                    }
                });
            });

            /**
             * 删除某条数据
             */
            $("#deleteSupplier").click(function () {
                var id = $(grid_selector).jqGrid('getGridParam', 'selrow');

                if (!id) {
                    layer.msg("提示：", "请选择一条信息");
                    return;
                }
                //询问框
                layer.confirm('将会把这条商品数据删除', {
                    btn: ['确定', '取消'] //按钮
                }, function () {
                    var rowData = $(grid_selector).jqGrid('getRowData', id);
//                    rowData.id = rowData.id.split('>')[1].split('<')[0];
                    queryModel.id = rowData.id;
                    layer.load(1);
                    $.ajax({
                        url: '${contextPath}/',
                        type: 'post',
                        data: queryModel,
                        dataType: 'json',
                        success: function (data) {
                            layer.closeAll('loading');
                            if (data.success) {
                                layer.msg('删除成功', {icon: 1});

                            } else {
                                layer.msg(data.message);
                            }
                            reload();

                        },
                        error: function (error) {
                            layer.closeAll('loading');
                            layer.msg("提示：", "服务器异常，稍后再试");
                        }

                    })

                }, function () {
                });
            });



        });
    });
</script>

<!-- 自动补全 -->
<script type="text/javascript" src="${contextPath}/static/statistics/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="${contextPath}/static/util/my-autocomplete-section.js"></script>


<!-- 商品下拉菜单 -->
<script type="text/javascript">
    /**
     * 下啦联动数据绑定 开始代码
     * @type {{parentId: string}}
     */
    $('#isExpInput').change(function () {
        app.yanType2 = []
        app.yanType3 = []
        app.yanType4 = []
        $("#commodityScreen").addClass("hide");
        queryModel.parentId = $("#isExpInput option:selected").val();
        querySubProdType2()
    });

    $('#isAuthInput').change(function () {
        app.yanType3 = []
        app.yanType4 = []
        $("#commodityScreen").addClass("hide");
        queryModel.parentId = $("#isAuthInput option:selected").val();
        querySubProdType3()
    });

    $('#isAuthInput1').change(function () {
        app.yanType4 = []
        $("#commodityScreen").addClass("hide");
        queryModel.parentId = $("#isAuthInput1 option:selected").val();
        querySubProdType4()
    });

    $('#isAuthInput2').change(function () {
        app.yanType5 = []
        $("#commodityScreen").addClass("hide");
        queryModel.parentId = "";
        queryModel.typeId = $("#isAuthInput2 option:selected").val();
        querySubProdType5()
    });

    var querySubProdType1 = function () {
        queryModel.parentId = '0';
        getSubProdType1(queryModel)
    }
    var querySubProdType2 = function () {
        getSubProdType2(queryModel)
    }
    var querySubProdType3 = function () {
        getSubProdType3(queryModel)
    }
    var querySubProdType4 = function () {
        getSubProdType4(queryModel)
    }
    var querySubProdType5 = function () {
        getSubProdType5(queryModel)
    }


    var getSubProdType1 = function (queryModel) {
        // console.log(queryModel)
//        layer.load(1)
        $.ajax({
            url: '${contextPath}/ktProd/getSubProdType',
            type: 'post',
            data: queryModel,
            success: function (data) {
//                layer.closeAll('loading');
                if (data.success == false){
                    layer.msg("获取出错："+data.message)
                    return
                }
                var dataArray = data;
                app.yanType1 = dataArray;
            },
            error: function (error) {
//                layer.closeAll('loading')
            }
        })
    }

    var getSubProdType2 = function (queryModel) {
        console.log(queryModel)
        $.ajax({
            url: '${contextPath}/ktProd/getSubProdType',
            type: 'post',
            data: queryModel,
            success: function (data) {
                if (data.success == false){
                    layer.msg("获取出错："+data.message)
                    return
                }
                var dataArray = data;
                app.yanType2 = dataArray;

            },
            error: function (error) {
            }
        })
    }

    var getSubProdType3 = function (queryModel) {
        console.log(queryModel)
//        layer.load(1)
        $.ajax({
            url: '${contextPath}/ktProd/getSubProdType',
            type: 'post',
            data: queryModel,
            success: function (data) {
//                layer.closeAll('loading');
                if (data.success == false){
                    layer.msg("获取出错："+data.message)
                    return
                }
                var dataArray = data;
                app.yanType3 = dataArray;

            },
            error: function (error) {
//                layer.closeAll('loading')
            }
        })
    }

    var getSubProdType4 = function (queryModel) {
        // console.log(queryModel)
//        layer.load(1)
        $.ajax({
            url: '${contextPath}/ktProd/getSubProdType',
            type: 'post',
            data: queryModel,
            success: function (data) {
//                layer.closeAll('loading');
                if (data.success == false){
                    layer.msg("获取出错："+data.message)
                    return
                }
                var dataArray = data;
                app.yanType4 = dataArray;

            },
            error: function (error) {
//                layer.closeAll('loading')
            }
        })
    }

    var getSubProdType5 = function (queryModel) {
        // console.log(queryModel)
//        layer.load(1)
        $.ajax({
            url: '${contextPath}/ktProd/getProdProperty',
            type: 'post',
            data: queryModel,
            success: function (data) {
//                layer.closeAll('loading');
                if (data.success == false){
                    layer.msg("获取出错："+data.message)
                    return
                }
                var dataArray = data;
                app.yanType5 = dataArray;

            },
            error: function (error) {
//                layer.closeAll('loading')
            }
        })
    }

    querySubProdType1(queryModel);

    /**
     * 下啦联动数据绑定 结束代码
     */
</script>

<!-- 数型插件 -->
<script type="text/javascript">

</script>

